package com.foreknow.springboot.threaddemo;

/**
 * @author xiaoming
 * @version jdk1.8
 * @date 2022/8/11 15:56
 * @function:
 */
public class Ticket extends Thread {
    private static int tickets = 100;
    @Override
    public void run() {
       while (true){
           //synchronize线程同步: 当某个线程正在执行时,其他线程可能会被修改票数
           //所以我们使用synchronized加锁,当前线程在执行时候，其他线程无法修改数据
           synchronized (Ticket.class){
           tickets--;
           if (tickets<=0){
               break;
           }
           try {
               Thread.sleep(60);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           System.out.println(getName()+": 卖出第"+tickets+"张票");
       }
       }
    }

    public static void main(String[] args) {
        Ticket t1 = new Ticket();
        Ticket t2 = new Ticket();
        Ticket t3 = new Ticket();
        Ticket t4 = new Ticket();
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t4.setName("窗口4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
